package Easy.Tree;

/**
 * @author: white-zhou
 * @date: 2024-09-19 17:27
 **/
public class DiameterOfBinaryTree {
    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    public int diameterOfBinaryTree(TreeNode root) {
        return dfs(root)[1];
    }

    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[]{0, 0};
        }
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        int depth = Math.max(left[0], right[0]) + 1;
        int diameter = Math.max(Math.max(left[1], right[1]), left[0] + right[0]);
        return new int[]{depth, diameter};
    }
}
